﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using AForge.Imaging.Filters;

namespace BulkImageSplitter
{
    /// <summary>
    /// A utility to bulk split compound images into parts based on a background filter.
    /// </summary>
    public class BulkSplitter
    {
        Action<string> _logAction;
        Action _processingCompleteAction;
        Splitter _splitter;

        public BulkSplitter(Action<string> logAction, Action processingCompleteAction)
        {
            _logAction = logAction;
            _processingCompleteAction = processingCompleteAction;

            _splitter = new Splitter(logAction);
        }
        
        /// <summary>
        /// The directory to search for images files in.
        /// </summary>
        public string InputDirectory { get; set; }

        /// <summary>
        /// The output directory.
        /// </summary>
        public string OutputDirectory 
        {
            get { return _splitter.OutputDirectory; }
            set { _splitter.OutputDirectory = value; }
        }

        /// <summary>
        /// The background filter.
        /// </summary>
        public ColorFiltering BackgroundFilter
        {
            get { return _splitter.BackgroundFilter; }
            set { _splitter.BackgroundFilter = value; }
        }

        /// <summary>
        /// The minimum acceptable size for detected images.
        /// </summary>
        public Size MinimumSize
        {
            get { return _splitter.MinimumSize; }
            set { _splitter.MinimumSize = value; }
        }

        public void Process()
        {
            _logAction(string.Format("Processing images in: '{0}'", InputDirectory));

            foreach (string file in Directory.GetFiles(InputDirectory))
            {
                _logAction(string.Format("Process file: '{0}'", file));
                Bitmap bitmap = null;

                try
                {
                    bitmap = (Bitmap)Bitmap.FromFile(file);
                }
                catch (Exception e)
                {
                    _logAction(string.Format("Skipping file: '{0}' - doesn't seem to be a valid image; '{1}'", file, e.Message));
                    continue;
                }

                _splitter.SplitImage(bitmap, file);
            }

            _processingCompleteAction();
        }
    }
}
